// MyFamily - XML based genealogy program.
// Copyright (C) 2006  Doug Swisher
// See the file COPYING.txt for license details.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Web.UI;

using DataModel;


namespace WebLib
{
    class SourcePage : WebPage
    {
        private static string CreateIndividualLink(FileNameBuilder namer, FamilyPersona persona)
        {
            if ( persona.Individual == null )
            {
                return persona.Name.ToString();
            }
            else
            {
                return GetIndividualLink( namer, persona.Individual );
            }
        }

        private static void WriteIndividuals(HtmlTextWriter writer, FamilySource source, FamilyInfo info, FileNameBuilder namer)
        {
            
            foreach ( var persona in info.Personas.Values )
            {  
                if (persona.Extract.Source.Id.Equals( source.Id ))
                {
                    if ( persona.Events.Count!=0 )
                    {
                        var table = new BlockTable("EVENT", "DATE") { BannerText = CreateIndividualLink( namer, persona) };

                        foreach (var e in persona.Events)
                        {
                            if (e.Source.Id.Equals(source.Id))
                            {
                                BlockTable.Row row = table.AddRow();
                                row[0] = e.Kind;
                                row[1] = e.Date;
                            }
                        }
                        table.Write(writer);
                    }
                    else
                    {
                        var table = new BlockTable { BannerText = CreateIndividualLink(namer, persona) };
                        table.Write(writer);
                    } 
                }
            }

        }


        public static void Generate(FamilySource source, FileNameBuilder namer, FamilyInfo info)
        {
            FileInfo page = namer.GetPageName(source);

            using (HtmlTextWriter writer = new HtmlTextWriter(page.CreateText(), string.Empty))
            {
                WriteHeader(writer, source.Title);
                WriteTitle( writer, source.Title );
                WriteMenu(writer, namer, info);

                writer.AddAttribute(HtmlTextWriterAttribute.Id, "GeneratedContent");
                writer.RenderBeginTag(HtmlTextWriterTag.Div);
                WriteIndividuals(writer, source, info, namer);

                writer.RenderEndTag();
                writer.Close();
            }
        }

    }
}